package com.bing.bingPro.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
public class ProTerminalTestSaveService {
    /**
    * 保存测试明细到本地
     **/
    public String saveFileToLocal(String filePath, MultipartFile file,String province,String vendor,String gatewayModel,String version) {
        File localFile = new File(filePath);
        //先创建目录
        localFile.mkdirs();
        LocalDateTime date = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // 获取当前日期
        String originalFilename = file.getOriginalFilename();
        String path = String.format("%s/%s%s%s%s%s%s",filePath,date.format(formatter),province+"_",vendor+"_",gatewayModel+"_",version+"_",originalFilename);
        log.info("create Local File path = {}", path);
        localFile = new File(path);
        FileOutputStream fos = null;
        InputStream in = null;
        try {
            if(localFile.exists()){
                //如果文件存在删除文件
                localFile.mkdirs();
                boolean delete = localFile.delete();
                if (!delete){
                    log.error("Delete exist file \"{}\" failed!!!",path,new Exception("Delete exist file \""+path+"\" failed!!!"));
                }
            }
            //创建文件
            if(!localFile.exists()){
                //如果文件不存在，则创建新的文件
                boolean newFile = localFile.createNewFile();
                if (newFile){
                    log.info("Create file successfully,the file is {}",path);
                }
            }
            //创建文件成功后，写入内容到文件里
            fos = new FileOutputStream(localFile);
            in = file.getInputStream();
            byte[] bytes = new byte[1024];
            int len = -1;
            while((len = in.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
            }
            fos.flush();
            log.info("Reading uploaded file and buffering to local successfully!");
            return path;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.info("Reading uploaded file and buffering to local failed! code:007");
        } catch (IOException e) {
            e.printStackTrace();
            log.info("Reading uploaded file and buffering to local failed! code:008");
        }finally {
            try {
                if(fos != null) {
                    fos.close();
                }
                if(in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("InputStream or OutputStream close error : %s", e);
            }
        }
        log.info("Reading uploaded file and buffering to local successfully!");
        return path;
    }
}
